<template>
    <el-form :model="form" :rules="rules" ref="formRef" label-width="120px" class="sheep-add-form">
        <h3>基本信息</h3>
        <el-row :gutter="20">
            <el-col :span="8">
                <el-form-item label="耳号" prop="EarNumber" required>
                    <el-input v-model="form.EarNumber" placeholder="请输入耳号" />
                </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item label="品种" prop="Variety" required>
                    <el-select v-model="form.Variety" placeholder="请选择品种">
                        <el-option v-for="item in breedOptions" :key="item" :label="item" :value="item" />
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item label="性别" prop="Sex" required>
                    <el-select v-model="form.Sex" placeholder="请选择性别">
                        <el-option label="公" value="公" />
                        <el-option label="母" value="母" />
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item label="电子耳标号" prop="ELEarNumber">
                    <el-input v-model="form.ELEarNumber" placeholder="请输入电子耳标号" />
                </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item label="基因等级" prop="GeneticLevel">
                    <el-select v-model="form.GeneticLevel" placeholder="请选择基因等级">
                        <el-option v-for="item in geneLevelOptions" :key="item" :label="item" :value="item" />
                    </el-select>
                </el-form-item>
            </el-col>
        </el-row>

        <h3>出生信息</h3>
        <el-row :gutter="20">
            <el-col :span="8">
                <el-form-item label="父亲耳号" prop="FatherEarNumber">
                    <el-select v-model="form.FatherEarNumber" placeholder="请选择父亲耳号" filterable clearable>
                        <el-option v-for="item in earNumberOptions" :key="item.Id" :label="item.name || item.EarNumber"
                            :value="item.Name || item.EarNumber" />
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item label="母亲耳号" prop="MotherEarNumber">
                    <el-select v-model="form.MotherEarNumber" placeholder="请选择母亲耳号" filterable clearable>
                        <el-option v-for="item in earNumberOptions" :key="item.Id" :label="item.name || item.EarNumber"
                            :value="item.Name || item.EarNumber" />
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item label="出生日期" prop="Birthday" required>
                    <el-date-picker v-model="form.Birthday" type="date" placeholder="请选择出生日期" style="width: 100%;" />
                </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item label="入场日期" prop="EntryDate">
                    <el-date-picker v-model="form.EntryDate" type="date" placeholder="请选择入场日期" style="width: 100%;" />
                </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item label="出生场地" prop="BirthPlace">
                    <el-input v-model="form.BirthPlace" placeholder="本场" />
                </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item label="出生重(公斤)" prop="BirthWeight" required>
                    <el-input v-model="form.BirthWeight" placeholder="请输入出生重" />
                </el-form-item>
            </el-col>
        </el-row>
        <el-form-item>
            <el-button type="primary" @click="handleSubmit">保存</el-button>
            <el-button @click="handleReset">重置</el-button>
        </el-form-item>
    </el-form>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
// import { addSheepFiles, getBreedOptions, getGeneLevelOptions, getEarNumberList } from '@/api/sheepFiles'
import { useRouter } from 'vue-router'
import { Sheep_BreedingWrite, Sheep_BreedingRead } from '@/utils/Interceptors'
const router = useRouter()
const formRef = ref()
const form = reactive({
    EarNumber: '',
    ELEarNumber: '',
    Variety: '',
    Sex: '',
    GeneticLevel: '',
    Birthday: '',
    FatherEarNumber: '',
    MotherEarNumber: '',
    GrowthStage: '乳羊',
    SheepType: "后裔",
    ReproductiveStatus: "--",
    PregnancyTest: "--",
    PregnancyDays: 0,
    EntryDate: '',
    BirthPlace: '本场',
    BirthWeight: '',
})

const rules = {
    EarNumber: [
        { required: true, message: '请输入耳号', trigger: 'blur' },
        { min: 1, max: 50, message: '耳号长度在1到50个字符', trigger: 'blur' }
    ],
    Variety: [
        { required: true, message: '请选择品种', trigger: 'change' }
    ],
    Birthday: [
        { required: true, message: '请选择出生日期', trigger: 'change' }
    ],
    BirthWeight: [
        { required: true, message: '请输入出生重', trigger: 'blur' },
        { pattern: /^\d+(\.\d+)?$/, message: '请输入有效的数字', trigger: 'blur' }
    ],
    Sex: [
        { required: true, message: '请选择性别', trigger: 'change' }
    ],
}

const breedOptions = ref<string[]>(['杜泊', '澳洲白', '萨福克', '杜湖', '杜杜湖', '萨杜湖', '澳湖', '湖羊', '澳杜湖'])
const geneLevelOptions = ref<string[]>(['后备级', '核心级', '生产级', '未定级'])
const earNumberOptions = ref<any[]>([])

// 获取耳号
const fetchEarNumbers = async () => {
    const res = await Sheep_BreedingRead.get('/api/EliminationInfo/GetSheepFilesIdEarNumber')
    if (res.data && res.data.code === 200) {
        earNumberOptions.value = res.data.data || []
    }
}
onMounted(async () => {
    // breedOptions.value = await getBreedOptions()
    // geneLevelOptions.value = await getGeneLevelOptions()
    // const res = await getEarNumberList()
    // if (res.data && res.data.code === 200) {
    //   earNumberOptions.value = res.data.data || []
    // }
    fetchEarNumbers()
})

const handleSubmit = () => {
    formRef.value.validate(async (valid: boolean) => {
        if (!valid) {
            ElMessage.warning('请检查表单填写是否完整')
            return
        }

        try {
            // 数据预处理
            const submitData = {
                ...form,
                // 确保数字字段为数字类型
                BirthWeight: parseFloat(form.BirthWeight) || 0,
                PregnancyDays: parseInt(form.PregnancyDays) || 0,
                // 确保日期格式正确
                Birthday: form.Birthday ? new Date(form.Birthday).toISOString().split('T')[0] : '',
                EntryDate: form.EntryDate ? new Date(form.EntryDate).toISOString().split('T')[0] : '',
                // 处理空值
                ELEarNumber: form.ELEarNumber || null,
                GeneticLevel: form.GeneticLevel || null,
            }

            console.log('提交数据:', submitData)

            const res = await Sheep_BreedingWrite.post('/api/SheepFiles/AddSheepFiles', submitData)
            console.log('API响应:', res.data)

            if (res.data && res.data.code === 200) {
                ElMessage.success(res.data.msg || '保存成功')
                router.push('/SheepFilesList')
            } else {
                ElMessage.error(res.data?.msg || '保存失败')
                console.error('保存失败详情:', res.data)
            }
        } catch (error: any) {
            console.error('保存异常:', error)
            if (error.response?.data?.msg) {
                ElMessage.error(error.response.data.msg)
            } else if (error.response?.data?.errors) {
                // 处理字段验证错误
                const errors = error.response.data.errors
                const errorMessages = Object.keys(errors).map(key =>
                    `${key}: ${errors[key].join(', ')}`
                ).join('\n')
                ElMessage.error(`字段验证失败:\n${errorMessages}`)
            } else {
                ElMessage.error('保存失败，请稍后重试')
            }
        }
    })
}

const handleReset = () => {
    formRef.value?.resetFields()
    // 重置为默认值
    Object.assign(form, {
        EarNumber: '',
        ELEarNumber: '',
        Variety: '',
        GeneticLevel: '',
        Birthday: '',
        SheepType: "种公",
        ReproductiveStatus: "--",
        PregnancyTest: "--",
        PregnancyDays: 0,
        EntryDate: '',
        BirthPlace: '本场',
        BirthWeight: '',

    })
}
</script>

<style scoped>
.sheep-add-form {
    background: #fff;
    padding: 24px;
    border-radius: 8px;
    max-width: 1200px;
    margin: 0 auto;
}

h3 {
    margin: 20px 0 10px 0;
    font-weight: bold;
}
</style>
